﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Emgu.CV;
using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using System.Security.Cryptography;
using System.Net;
using RestSharp;
using Newtonsoft.Json;
using System.Net.Http;

namespace MyOCR.Picture
{
    //https://ai.baidu.com/tech/ocr/
    class BaiDu_PictureHandleOCR :PictureHandle
    {
        public BaiDu_PictureHandleOCR()
        {

        }

        public override string IdentifyImage(Image img)
        {
            string base64img;

            var client = new RestClient("https://aip.baidubce.com/rest/2.0/ocr/v1/general_basic?access_token=" + getAccessToken());
            var request = new RestRequest(Method.POST);

            request.Timeout = 10000;
            request.AddHeader("content-type", "application/x-www-form-urlencoded");
            // base64 string file picture,too long in the case we will omit string
            var bmp = GrayscaleImage(img);
            base64img = ImageToBase64(bmp);

            request.AddParameter("image", base64img);

            IRestResponse response = client.Execute(request);

            //解析获取的json
            var lst = new List<string>();
            var content = response.Content;
            dynamic json = JsonConvert.DeserializeObject(content);
            foreach (var item in json.result)
            {
                lst.Add(item.content.ToString());
            }
            return string.Join("\r\n", lst);
        }

        /// <summary>
        /// 将图片转化为byte[]
        /// </summary>
        /// <param name="img">要转换的图片</param>
        /// <returns>byte[]</returns>
        private static byte[] ImgToBase64String(Image img)
        {
            Bitmap bmp = new Bitmap(img);
            MemoryStream ms = new MemoryStream();
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
            ms.Flush();
            byte[] bmpBytes = ms.ToArray();
            return bmpBytes;
        }

        /// <summary>
        /// 将图片转换为base64
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        private string ImageToBase64(Bitmap bmp)
        {
            MemoryStream ms = new MemoryStream();
            bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            byte[] arr = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(arr, 0, (int)ms.Length);
            ms.Close();
            string image = Convert.ToBase64String(arr);
            return image;
        }

        public String getAccessToken()
        {
            String authHost = "https://aip.baidubce.com/oauth/2.0/token";
            HttpClient client = new HttpClient();
            List<KeyValuePair<String, String>> paraList = new List<KeyValuePair<string, string>>();
            paraList.Add(new KeyValuePair<string, string>("grant_type", "client_credentials"));
            paraList.Add(new KeyValuePair<string, string>("client_id", Program._config.BaiDu_Api_Key));
            paraList.Add(new KeyValuePair<string, string>("client_secret", Program._config.BaiDu_Secret_Key));

            HttpResponseMessage response = client.PostAsync(authHost, new FormUrlEncodedContent(paraList)).Result;
            String result = response.Content.ReadAsStringAsync().Result;
            dynamic json = JsonConvert.DeserializeObject(result);
            return json.refresh_token;
        }

        /********************************↓翻译处理↓**********************************/

        protected override string getSign()
        {
            string sign = string.Format("{0}{1}{2}{3}", "20190612000306732", msg, "1435660288", "Xiorq8HxOIwiVHn2la_W");
            var md5 = new MD5CryptoServiceProvider();
            var result = Encoding.UTF8.GetBytes(sign);
            var output = md5.ComputeHash(result);
            return BitConverter.ToString(output).Replace("-", "").ToLower();
        }

        private string GetJson()
        {
            var client = new RestClient("http://api.fanyi.baidu.com");
            var request = new RestRequest("/api/trans/vip/translate", Method.GET);
            request.AddParameter("q", msg);
            request.AddParameter("from", "en");
            request.AddParameter("to", "zh");
            request.AddParameter("appid", "20190612000306732");
            request.AddParameter("salt", "1435660288");
            request.AddParameter("sign", getSign());
            IRestResponse response = client.Execute(request);
            return response.Content;
        }

        public string GetResult(string msg)
        {
            var lst = new List<string>();
            var content = GetJson();
            dynamic json = JsonConvert.DeserializeObject(content);
            foreach (var item in json.trans_result)
            {
                lst.Add(item.dst.ToString());
            }
            return string.Join("\r\n", lst);
        }
    }
}
